<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />





  <link rel="alternate" href="/atom.xml" title="结网之路" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="本章顾名思义，讲了 Looper，Handler，以及线程之间的交互。
GitHub 地址：完成24章但未完成挑战完成24章挑战1完成24章挑战2

在本章，我们要使用一个新的线程，并且使用其中 Looper 来完成下载图片的工作。为什么不直接在 AsyncTask 的 doInBackground 中添加网络下载代码呢？那样就要每次下载一张，直到完成全部100张的下载。最后才会执行 onPos">
<meta property="og:type" content="article">
<meta property="og:title" content="Android编程权威指南（第二版）学习笔记（二十四）—— 第24章 Looper、Handler 和 HandlerThread">
<meta property="og:url" content="https://kniost.github.io/2017-02-15-cj0ag5y6w001tifs6pdnqqnhm/index.html">
<meta property="og:site_name" content="结网之路">
<meta property="og:description" content="本章顾名思义，讲了 Looper，Handler，以及线程之间的交互。
GitHub 地址：完成24章但未完成挑战完成24章挑战1完成24章挑战2

在本章，我们要使用一个新的线程，并且使用其中 Looper 来完成下载图片的工作。为什么不直接在 AsyncTask 的 doInBackground 中添加网络下载代码呢？那样就要每次下载一张，直到完成全部100张的下载。最后才会执行 onPos">
<meta property="og:updated_time" content="2017-03-14T07:11:16.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android编程权威指南（第二版）学习笔记（二十四）—— 第24章 Looper、Handler 和 HandlerThread">
<meta name="twitter:description" content="本章顾名思义，讲了 Looper，Handler，以及线程之间的交互。
GitHub 地址：完成24章但未完成挑战完成24章挑战1完成24章挑战2

在本章，我们要使用一个新的线程，并且使用其中 Looper 来完成下载图片的工作。为什么不直接在 AsyncTask 的 doInBackground 中添加网络下载代码呢？那样就要每次下载一张，直到完成全部100张的下载。最后才会执行 onPos">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://kniost.github.io/2017-02-15-cj0ag5y6w001tifs6pdnqqnhm/"/>





  <title> Android编程权威指南（第二版）学习笔记（二十四）—— 第24章 Looper、Handler 和 HandlerThread | 结网之路 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">结网之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">临渊羡鱼，不如退而结网</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://kniost.github.io/2017-02-15-cj0ag5y6w001tifs6pdnqqnhm/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="kniost">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="结网之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android编程权威指南（第二版）学习笔记（二十四）—— 第24章 Looper、Handler 和 HandlerThread
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-02-15T16:19:10+08:00">
                2017-02-15
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android编程权威指南学习笔记/" itemprop="url" rel="index">
                    <span itemprop="name">Android编程权威指南学习笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017-02-15-cj0ag5y6w001tifs6pdnqqnhm/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017-02-15-cj0ag5y6w001tifs6pdnqqnhm/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本章顾名思义，讲了 Looper，Handler，以及线程之间的交互。</p>
<p>GitHub 地址：<br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/c68af985ad2fed691ff399ec8ba4519dd4dcf8f7" target="_blank" rel="external">完成24章但未完成挑战</a><br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/c001631637043bcaf1d288a06c81988e03ecec11" target="_blank" rel="external">完成24章挑战1</a><br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/7323d8b21706f8398896f5fadd1a2612dd6c8b8b" target="_blank" rel="external">完成24章挑战2</a></p>
</blockquote>
<p>在本章，我们要使用一个新的线程，并且使用其中 Looper 来完成下载图片的工作。为什么不直接在 AsyncTask 的 doInBackground 中添加网络下载代码呢？那样就要每次下载一张，直到完成全部100张的下载。最后才会执行 onPostExecute(…)方法，让所有下载的图片全部显示在 RecyclerView 视图中，这样既耗时又耗内存。AsyncTask 是执行后台线程的最简单方式，但它不适用于那些重复且长时间运行的任务。</p>
<h1 id="1-各种定义"><a href="#1-各种定义" class="headerlink" title="1. 各种定义"></a>1. 各种定义</h1><h2 id="1-1-Looper"><a href="#1-1-Looper" class="headerlink" title="1.1 Looper"></a>1.1 Looper</h2><p>Android 系统中，线程有一个消息队列(message queue)。使用消息队列的线程叫作消息循环(message loop)。消息循环会循环检查队列上是否有新消息。消息循环由线程和 looper 组成。Looper 对象管理着线程的消息队列。<br>主线程就是个消息循环，因此也拥有 looper。主线程的所有工作都是由其 looper 完成的。looper 不断从消息队列中抓取消息，然后完成消息指定的任务。</p>
<h2 id="1-2-Message"><a href="#1-2-Message" class="headerlink" title="1.2 Message"></a>1.2 Message</h2><p>Message 类是 Handler 的子类用于 Handler 传递消息，它有好几个实例变量，其中有三个需在实现时定义。 </p>
<ul>
<li>what:用户定义的 int 型消息代码，用来描述消息。</li>
<li>obj:随消息发送的用户指定对象。</li>
<li>target:处理消息的 Handler。<br>Message 的 target 是 Handler 类的一个实例。创建 Message 时，它会自动与一个 Handler 相关联。Message 待处理时，Handler 对象负责触发消息处理事件。</li>
</ul>
<h2 id="1-3-Handler"><a href="#1-3-Handler" class="headerlink" title="1.3 Handler"></a>1.3 Handler</h2><p>Handler 可看作 message handler 的简称。Handler 不仅仅是处理 Message 的目标(target)，也是创建和发布 Message 的接口。创建 Handler 时，它会自动和该线程的 Looper 相关联。</p>
<h2 id="1-4-三者关系"><a href="#1-4-三者关系" class="headerlink" title="1.4 三者关系"></a>1.4 三者关系</h2><ul>
<li>一个 Thread 仅有一个 Looper，也就是一个消息队列</li>
<li>一个 Thread 可以有多个 Handler，共用一个消息队列</li>
<li>一个 Message 只对应一个 Handler，一个 Handler 可以有多个 Message</li>
</ul>
<h2 id="1-5-一个典型-Looper-的处理过程"><a href="#1-5-一个典型-Looper-的处理过程" class="headerlink" title="1.5 一个典型 Looper 的处理过程"></a>1.5 一个典型 Looper 的处理过程</h2><p>首先需要准备好 Looper，然后建立一个其他线程能引用的 Handler，在需要的时候让 Handler 发消息给 Looper 让其执行。</p>
<h1 id="2-HandlerThread"><a href="#2-HandlerThread" class="headerlink" title="2. HandlerThread"></a>2. HandlerThread</h1><p>HandlerThread 类帮我们完成了建立 Looper 的过程，因此，只要继承它就能省去一些工作，并且避免一些风险。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// ThumbnailDowloadler.java 省略了许多内容</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThumbnailDowloader</span>&lt;<span class="title">T</span>&gt; <span class="keyword">extends</span> <span class="title">HandlerThread</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> MESSAGE_DOWNLOAD = <span class="number">0</span>;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> Boolean mHasQuit = <span class="keyword">false</span>;</div><div class="line">    <span class="keyword">private</span> Handler mRequestHandler;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onLooperPrepared</span><span class="params">()</span> </span>&#123;</div><div class="line">    	<span class="comment">// 新建一个 Handler</span></div><div class="line">        mRequestHandler = <span class="keyword">new</span> Handler() &#123;</div><div class="line">            <span class="meta">@Override</span></div><div class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleMessage</span><span class="params">(Message msg)</span> </span>&#123;</div><div class="line">                <span class="keyword">if</span> (msg.what == MESSAGE_DOWNLOAD) &#123;</div><div class="line">                    <span class="comment">// get a photo and refresh view</span></div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">        &#125;;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">queueThumbnail</span><span class="params">(T target, String url)</span> </span>&#123;</div><div class="line">        <span class="comment">// 外部调用，发消息给 Handler</span></div><div class="line">        mRequestHandler.obtainMessage(MESSAGE_DOWNLOAD, target)</div><div class="line">                    .sendToTarget();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clearQueue</span><span class="params">()</span> </span>&#123;</div><div class="line">        mRequestHandler.removeMessages(MESSAGE_DOWNLOAD);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>主线程中是这样的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">mThumbnailDownloader = <span class="keyword">new</span> ThumbnailDownloader&lt;&gt;();</div><div class="line">mThumbnailDownloader.start();</div><div class="line">mThumbnailDownloader.getLooper();</div><div class="line"><span class="comment">// 在需要的时候调用</span></div><div class="line">mThumbnailDownloader.queueThumbnail(holder, url);</div></pre></td></tr></table></figure>
<h1 id="3-线程交互"><a href="#3-线程交互" class="headerlink" title="3. 线程交互"></a>3. 线程交互</h1><p>主线程现在能够适时调用这个线程的方法，用于下载图片了。但是还存在一个问题，那就是下载线程下载完一个任务以后如何更新视图呢？我们知道 UI 只能在主线程里更新，所以我们采用在主线程里声明一个 Handler，传递给下载线程，让下载线程在下载完成后在主线程执行更新操作。因为不能直接引用主线程的方法，故而在这里用到了回调。</p>
<h2 id="3-1-下载线程中"><a href="#3-1-下载线程中" class="headerlink" title="3.1 下载线程中"></a>3.1 下载线程中</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// ThumbnailDownloader，也就是下载线程中</span></div><div class="line"></div><div class="line"><span class="comment">// 成员声明</span></div><div class="line"><span class="keyword">private</span> Handler mResponseHandler;</div><div class="line"><span class="keyword">private</span> ThumbnailDowloadListener&lt;T&gt; mThumbnailDownloadListener;</div><div class="line"></div><div class="line"><span class="comment">// 回调接口</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ThumbnailDowloadListener</span>&lt;<span class="title">T</span>&gt; </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">void</span> <span class="title">onThumbnailDownloaded</span><span class="params">(T target, Bitmap thumbnail)</span></span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setThumbnailDownloaderListener</span><span class="params">(ThumbnailDowloadListener&lt;T&gt; listener)</span> </span>&#123;</div><div class="line">    mThumbnailDownloadListener = listener;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 通过构造函数传递主线程的 Handler</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="title">ThumbnailDowloader</span><span class="params">(Handler responseHandler)</span> </span>&#123;</div><div class="line">    <span class="keyword">super</span>(TAG);</div><div class="line">    mResponseHandler = responseHandler;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这样，主线程通过调用这些方法，就能够让下载线程获取到主线程的 Handler 和回调接口实例。</p>
<h2 id="3-2-主线程中"><a href="#3-2-主线程中" class="headerlink" title="3.2 主线程中"></a>3.2 主线程中</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 成员声明</span></div><div class="line"><span class="keyword">private</span> ThumbnailDowloader&lt;PhotoHolder&gt; mThumbnailDownloader;</div><div class="line"></div><div class="line"><span class="comment">// 传递实例给下载线程</span></div><div class="line"><span class="comment">// 这个 Handler 在主线程中建立，所以是和主线程 Looper 相关联的</span></div><div class="line">Handler responseHandler = <span class="keyword">new</span> Handler(); </div><div class="line">mThumbnailDownloader = <span class="keyword">new</span> ThumbnailDowloader&lt;&gt;(responseHandler);</div><div class="line">mThumbnailDownloader.setThumbnailDownloaderListener(</div><div class="line">	<span class="keyword">new</span> ThumbnailDowloader.ThumbnailDowloadListener&lt;PhotoHolder&gt;() &#123;</div><div class="line">	   	<span class="meta">@Override</span></div><div class="line">	   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onThumbnailDownloaded</span><span class="params">(PhotoHolder target, Bitmap thumbnail)</span> </span>&#123;</div><div class="line">	   		Drawable drawable = <span class="keyword">new</span> BitmapDrawable(getResources(), thumbnail);</div><div class="line">			target.bindDrawable(drawable);</div><div class="line">    	&#125;</div><div class="line">	&#125;</div><div class="line">);</div></pre></td></tr></table></figure>
<h2 id="3-3-在下载线程中给主线程-Looper-发送消息"><a href="#3-3-在下载线程中给主线程-Looper-发送消息" class="headerlink" title="3.3 在下载线程中给主线程 Looper 发送消息"></a>3.3 在下载线程中给主线程 Looper 发送消息</h2><p>现在，通过 mResponseHandler，下载线程能够访问与主线程 Looper 绑定的 Handler。同时，还有 ThumbnailDownloadListener 使用返回的 Bitmap 执行 UI 更新操作。具体来说， 就是通过 onThumbnailDownloaded 实现，使用新下载的 Bitmap 来设置 PhotoHolder 的 Drawable。<br>和在下载线程上把下载图片的请求放入消息队列类似，我们也可以返回定制 Message 给主线程，要求显示已下载图片。不过，这需要另一个 Handler 子类，以及一个 handleMessage(…) 覆盖方法。方便起见，我们转而使用另一个方便的 Handler 方法——post(Runnable)。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">mResponseHandler.post(<span class="keyword">new</span> Runnable() &#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span> (mRequestMap.get(target) != url ||</div><div class="line">                mHasQuit) &#123;</div><div class="line">            <span class="keyword">return</span>;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        mRequestMap.remove(target);</div><div class="line">        mThumbnailDownloadListener.onThumbnailDownloaded(target, bitmap);</div><div class="line">    &#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>在这里，新建的 Runnable 对象会被当成 Message 的回调方法，直接执行 run() 方法，所以相当于发送一个消息，里面写明了怎么做，而不是把对象和消息类型发给 Handler，让 Handler 决定怎么做。</p>
<h1 id="4-挑战练习"><a href="#4-挑战练习" class="headerlink" title="4. 挑战练习"></a>4. 挑战练习</h1><h2 id="4-1-缓存层的添加"><a href="#4-1-缓存层的添加" class="headerlink" title="4.1 缓存层的添加"></a>4.1 缓存层的添加</h2><p>首先我们能够意识到，这个缓存应该放在下载线程中，因为所有下载的处理都在其中。LruCache 是一种类似键值对的存在，在图片缓存中，我们理所应当地可以将图片的 url 作为键，对应的 Bitmap 作为值，在下载一张图片之前先检查 Cache 中是否存在这个图片，不存在再下载。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 其中省略了之前写过的大量过程</span></div><div class="line"></div><div class="line"><span class="keyword">private</span> LruCache&lt;String, Bitmap&gt; mCache;</div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onLooperPrepared</span><span class="params">()</span> </span>&#123;</div><div class="line">	……</div><div class="line">	<span class="comment">// 建立 Cache</span></div><div class="line">    <span class="keyword">int</span> maxCacheSize = <span class="number">4</span> * <span class="number">1024</span> * <span class="number">1024</span>; <span class="comment">// 4MiB</span></div><div class="line">    mCache = <span class="keyword">new</span> LruCache&lt;&gt;(maxCacheSize);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">handleRequest</span><span class="params">(<span class="keyword">final</span> T target)</span> </span>&#123;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        <span class="keyword">final</span> String url = mRequestMap.get(target);</div><div class="line"></div><div class="line">        <span class="keyword">if</span> (url == <span class="keyword">null</span>) &#123;</div><div class="line">            <span class="keyword">return</span>;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="keyword">final</span> Bitmap bitmap;</div><div class="line">        <span class="keyword">if</span> (mCache.get(url) == <span class="keyword">null</span>) &#123;</div><div class="line">            <span class="keyword">byte</span>[] bitmapBytes = <span class="keyword">new</span> FlickrFetchr().getUrlBytes(url);</div><div class="line">            bitmap = BitmapFactory</div><div class="line">                    .decodeByteArray(bitmapBytes, <span class="number">0</span>, bitmapBytes.length);</div><div class="line">            Log.i(TAG, <span class="string">"Bitmap created"</span>);</div><div class="line"></div><div class="line">            mCache.put(url, bitmap);</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            bitmap = mCache.get(url);</div><div class="line">            Log.i(TAG, <span class="string">"Bitmap from cache"</span>);</div><div class="line">        &#125;</div><div class="line">        ……</div><div class="line">    &#125; <span class="keyword">catch</span> (IOException ioe) &#123;</div><div class="line">        Log.e(TAG, <span class="string">"Error downloading image"</span>, ioe);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="4-2-预加载"><a href="#4-2-预加载" class="headerlink" title="4.2 预加载"></a>4.2 预加载</h2><p>我用了较为笨的方法实现简单的预加载，那就是在 onBindViewHolder 的时候挨个加载对应 item 的前十个和后十个并放到缓存中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 下载线程中的方法</span></div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">handlePreload</span><span class="params">(String url)</span> </span>&#123;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        <span class="keyword">if</span> (url == <span class="keyword">null</span>) &#123;</div><div class="line">            <span class="keyword">return</span>;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="keyword">if</span> (mCache.get(url) == <span class="keyword">null</span>) &#123;</div><div class="line">            <span class="keyword">byte</span>[] bitmapBytes = <span class="keyword">new</span> FlickrFetchr().getUrlBytes(url);</div><div class="line">            Bitmap bitmap = BitmapFactory</div><div class="line">                    .decodeByteArray(bitmapBytes, <span class="number">0</span>, bitmapBytes.length);</div><div class="line">            mCache.put(url, bitmap);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">    &#125; <span class="keyword">catch</span> (IOException ioe) &#123;</div><div class="line">        Log.e(TAG, <span class="string">"Error preloading image"</span>, ioe);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 主线程中的调用</span></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onBindViewHolder</span><span class="params">(PhotoHolder holder, <span class="keyword">int</span> position)</span> </span>&#123;</div><div class="line">	……</div><div class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = Math.max(<span class="number">0</span>, position - <span class="number">10</span>);</div><div class="line">            i &lt; Math.min(mGalleryItems.size() - <span class="number">1</span>, position + <span class="number">10</span>);</div><div class="line">            i ++ ) &#123;</div><div class="line">        Log.i(TAG, <span class="string">"Preload position"</span> + i);</div><div class="line">        mThumbnailDownloader.queuePreloadThumbnail(mGalleryItems.get(i).getUrl());</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017-02-11-cj0ag5y6s001nifs6ztgicoai/" rel="next" title="Android编程权威指南（第二版）学习笔记（二十三）—— 第23章 HTTP 与后台任务">
                <i class="fa fa-chevron-left"></i> Android编程权威指南（第二版）学习笔记（二十三）—— 第23章 HTTP 与后台任务
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017-02-20-cj0ag5y6v001qifs6w86i124r/" rel="prev" title="Android编程权威指南（第二版）学习笔记（二十五）—— 第25章 搜索">
                Android编程权威指南（第二版）学习笔记（二十五）—— 第25章 搜索 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread"></div>
<script>

/**
*  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
*  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://kniost-comment-github.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
                                
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="kniost" />
          <p class="site-author-name" itemprop="name">kniost</p>
           
              <p class="site-description motion-element" itemprop="description">kniost 的成长与疑惑</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-各种定义"><span class="nav-text">1. 各种定义</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-Looper"><span class="nav-text">1.1 Looper</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-Message"><span class="nav-text">1.2 Message</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-3-Handler"><span class="nav-text">1.3 Handler</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-4-三者关系"><span class="nav-text">1.4 三者关系</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-5-一个典型-Looper-的处理过程"><span class="nav-text">1.5 一个典型 Looper 的处理过程</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-HandlerThread"><span class="nav-text">2. HandlerThread</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-线程交互"><span class="nav-text">3. 线程交互</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-下载线程中"><span class="nav-text">3.1 下载线程中</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-主线程中"><span class="nav-text">3.2 主线程中</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-在下载线程中给主线程-Looper-发送消息"><span class="nav-text">3.3 在下载线程中给主线程 Looper 发送消息</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-挑战练习"><span class="nav-text">4. 挑战练习</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-缓存层的添加"><span class="nav-text">4.1 缓存层的添加</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-预加载"><span class="nav-text">4.2 预加载</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">kniost</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'kniost-comment-github';
      var disqus_identifier = '2017-02-15-cj0ag5y6w001tifs6pdnqqnhm/';

      var disqus_title = "Android编程权威指南（第二版）学习笔记（二十四）—— 第24章 Looper、Handler 和 HandlerThread";


      function run_disqus_script(disqus_script) {
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');

      
        var disqus_config = function () {
            this.page.url = disqus_url;
            this.page.identifier = disqus_identifier;
            this.page.title = disqus_title;
        };
        run_disqus_script('embed.js');
      

    </script>
  










  
  

  

  

  

  


  

</body>
</html>
